import json
class Atm():
    """
    模拟ATM取款机，实现存钱取钱，登陆，退出，查询
    """
    def __init__(self): #初始化属性
        self.username = '' #用户名
        self.password = '' #用户密码
        self.fn = 1
        self.aka = 1
        self.file = 'user.txt'

    def query1(self,x=0,fs='None'): #打开文件
        fn = 0
        #新建文件
        if x == 0:
            f = open(self.file,'w')
            if fs != 'None':
                f.write(fs+'\n')
            f.close()
        #读取文件
        elif x == 1:
            f = open(self.file,'r')
            fn = f.readlines()
            f.close()
        #追加文件
        elif x == 2:
            f = open(self.file,'a')
            if fs != 'None':
                f.writelines(fs+'\n')
            f.close()
        return fn

    def query(self,username=None):
        try:
            fs = self.query1(1)
        except FileNotFoundError:
            fs = self.query1()
        if fs:
            for i in fs:
                cbc = dict(list(eval(i)))
                if username == cbc['username'] and self.aka == 2:
                    print(cbc['username'])

    def sign(self,mess='0',fn=1): #注册用户信息
        lists = []
        if fn == 1 and mess == '0' or fn == 1 and mess == '1':
            while True:
                self.name = input('请输入姓名：')
                if len(self.name) > 0 and len(self.name) < 5:
                    break
                else:
                    print('长度约束在0-5位字符...')
        if fn == 1 and mess == '0' or fn == 1 and mess == '2':
            while True:
                self.age = input("您的年龄(1-120)：")
                try:
                    self.age = int(self.age)
                    if self.age > 0 and self.age<= 120:
                        break
                    else:
                        print("请按约束输入...")
                except:
                    print('-'*9,'输入有误,请重新输入','-'*9)
        if fn == 1 and mess == '0' or fn == 1 and mess == '3':
            while True:
                self.username = input("请输入用户名：")
                if len(self.username) > 0 and len(self.username) <= 8:
                    try:
                        self.username = int(self.username)
                        print('error:不能为纯数字')
                    except:
                        break
                else:
                    print("错误提示：用户名输入限制在1-8位...")
            try:
                f = self.query1(1)
            except:
                self.query1()
                f = self.query1(1)
            for i in f:
                dicts = dict(eval(i))
                lists.append(dicts.get('username'))
                while self.username.lower() == dicts.get('username'):
                    self.username = input('用户名已存在...\n请重新输入：')
        if fn == 1 and mess == '0' or fn == 1 and mess == '4':
            while True:
                    self.password = input("请设置密码：")
                    if len(self.password) > 0 and len(self.password) <= 6:
                        break
                    else:
                        print('错误提示：密码限制输入1-6位...')
            password1 = input("请再次输入密码：")
            while self.password != password1:
                password1 = input("两次输入密码不一致，请重新输入:")
        else:
            print('您的输入有误...')
        message = input("信息将保存，确认不在修改吗?\nY/N:")
        if message.lower() == 'y':
            users = [['name', self.name], ['age', self.age], ['username', self.username], ['password', self.password]]
            self.query1(2,str(users))
            print('-'*39+'\n注册成功，请登录...\n')
        elif message.lower() == 'n':
            mess = input("全部修改请输入0，您可选择修改：1.姓名，2.年龄，3.用户名，4.密码：")
            self.sign(mess)

    def login(self,x=0):    #登陆
        try:
            f = self.query1(1)
        except FileNotFoundError:
            self.query1()
            print('-'*39+'\n初始化...\n'+'.'*39)
            return
        ds = {}
        x += 1
        if x <=3:
            username = input('请输入用户名：')
            for i in f:
                cbc = dict(eval(i))
                ds[cbc.get('username')] = cbc
            #print(ds)
            if username in set(ds):
                if username == ds[username]['username']:
                    self.username = username
                    password = input('请输入登陆密码：')
                    s = 1
                    if password == ds[username]['password']:
                        self.aka = 2
                        print('.'*39)
                    while password != ds[username]['password'] and s <=4:
                        if s == 4:
                            break
                        password = input('密码输入错误，请重新输入...\n输入回车退出：')
                        if password.lower() == '':
                            break
            else:
                print('你的输入有误，请重新输入...')
                self.login(x)
        else:
            print('='*39+"\n多次输入错误，退出登陆...\n"+'='*39+'\n'+'.'*39)


    def money(self,s=0):
        try:
            f = self.query1(1)
        except:
            self.query1()
            print('-' * 39 + '\n初始化...\n' + '.' * 39)
            return
        if s == 0:
            print('-'*39+"\n{0:<10}{1:<10}".format('1.账户信息','2.账户余额'))
            n = input('-'*39+"\n请选择：")
            if n == '1':
                pass
            elif n == '2':
                for i in f:
                    dicts = dict(eval(i))
                    if self.username == dicts['username']:
                        print('.'*39)
                        print("用户名：{:<10}".format(dicts['username'],))
                        print('姓名：{0:<5}年龄：{1:<5}余额：{2:^5}元'.format(dicts['name'],dicts['age'],dicts.get('money',0)))
                        break
            else:
                print('输入无效...请重新输入...')
        else:
            k = input('输入要操作的数额:')
            while True:
                try:
                    k = int(k)
                    if s == 2:
                        k = 0-k
                    break
                except:
                    print('请输入整数:')
            for i in f:
                dicts =dict(eval(i))
                if self.username == dicts['username']:
                    money = int(dicts.get('money',0)) + k
                    if money >= 0:
                        dicts['money'] = money
                        l = str(list(dicts.items()))
                        self.query1(0, l)
                        print('-'*39+'\n余额：{:^5}元\n'.format(dicts.get('money', 0))+'.'*39)
                    else:
                        print('-'*39+'\n余额不足...\n'+"."*39)
                else:
                    l = str(list(dicts.items()))
                    self.query1(0, l)

    def showui(self):
        """ATM系统"""
        print('=' * 15, "ATM系统", '=' * 15)
        print("{0:1}{1:13}{2:14}{3:}".format(' ', "1.登录", "2.注册", '3.查询'))
        print("{0:1}{1:13}{2:14}{3:}".format(' ', '4.存钱', '5.取钱', '6.退出'))
        print('=' * 39)
        key = input("请输入对应选择：")
        if key == '1':
            self.login()
            if self.aka == 2:
                print('登陆成功...\n'+'.'*39)
        elif key == '2':
            self.sign()
        elif key == '3':
            if self.aka == 2:
                self.money(0)
            else:
                print('请先登录...')
        elif key == '4':
            if self.aka == 2:
                self.money(1)
            else:
                print('请先登录...')
        elif key == '5':
            if self.aka == 2:
                self.money(2)
            else:
                print('请先登录...')
        elif key == '6':
            self.aka = 0
        else:
            print('您的输入无效...')
        if self.aka != 0:
            self.showui()



a = Atm()
a.showui()